package net.zjitc.reggiebymeme.controller;

import lombok.extern.slf4j.Slf4j;
import net.zjitc.reggiebymeme.common.R;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("common")
public class CommonController {
    private final String basePath = System.getProperty("user.dir") + "/src/main/resources/img/";

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info("文件上传：" + file.toString());
        //根据我们获得的文件目录，找到相对应的图片
        //转换为我们赋予的名字，保存在服务器中
        String originalFilename = file.getOriginalFilename();
        //获得原始名称后，取其后缀名。？为什么要取后缀名？
        //你需要给他赋值一个名字，这个名字你得知道是什么类型的
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;
        //String basePath = System.getProperty("user.dir") + "/src/main/resources/img/";
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();//make directory
        }
        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println();
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            ServletOutputStream outputStream = response.getOutputStream();
            String s = name.split("\\.")[1];
            response.setContentType("image/" + s);
            int len=0;
            byte[] bytes = new byte[1024];
            while((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
